package com.firstcards.web.controllers;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.firstcards.web.model.Category;
import com.firstcards.web.util.ResourceNotFoundException;

@Controller
@RequestMapping("/category")
public class Categories {

	private static Logger log = LoggerFactory.getLogger( Categories.class );


		static Map<Integer, Category> categoryMap =
			Collections.synchronizedMap(new TreeMap<Integer, Category>());
		static {
			categoryMap.put(1, new Category(1, "Restaurants", "Offering 2 for 1 on entrees"));
			categoryMap.put(2, new Category(2, "Golf courses", "2 individuals golf for the price of 1"));
			categoryMap.put(3, new Category(3, "Services", "Target for discount is dependent on service, but always 2 for the price of 1"));
			categoryMap.put(4, new Category(4, "Lodging", "2 rooms can be booked, while only paying the standard rate for 1"));
		}
	    @RequestMapping(value = "/", method = RequestMethod.GET)
	    public Collection<Category> getAll() {
	    	log.info("Request to getAll");
	    	return categoryMap.values();
	    }
	    
	    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
	    public Category getById(@PathVariable final int id) throws Exception{
	    	log.info("Request to get id " + id);
	    	
	    	if (categoryMap.containsKey(id)){
	    		return categoryMap.get(id);
	    	} 
	    	throw new ResourceNotFoundException("Category", new HashMap<String, String>() {{
	    		   put("id", "" + id);
	    		}});
	    }
	    
	    @ExceptionHandler(ResourceNotFoundException.class)
	    public void resourceNotFound(ResourceNotFoundException rnfe, HttpServletResponse response){
	    	try {
				response.sendError(404, rnfe.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	    

}